const action = require('./action')

// 这里维护所有的玩家
class Player {
  constructor() {
    this.maxPlayerNum = global.option.maxPlayerNum;
    this.playerList = {};
    this.playerUsername = [];
  }

  get(id) {
    return this.playerList[id];
  }

  add(socket) {
    if (this.playerList[socket.id]) {
      global.Core.socket.system('已经加入', 'red', socket);
      return;
    }
    if (global.Core.util.getObjLength(this.playerList) >= this.maxPlayerNum) {
      // 到达最大数
      global.Core.socket.system('游戏人数达到最大, 无法加入!', 'red', socket);
      global.Core.socket.emit('player.add.max');
      return;
    }

    this.playerList[socket.id] = new PS(socket);
  }

  leave(ps) {
    let player = this.playerList[ps.socket.id];
    if (!player) {
      return;
    }

    // 通知客户端玩家退出
    global.Core.socket.emit('message', {
      msg: `${player.data.username}退出了游戏, 滚他丫的，爱玩不玩。`,
      type: 'system',
      color: 'red'
    });
    global.Core.socket.emit('player.leave', {
      id: ps.socket.id
    });

    // 移除名称
    let usernameIndex = this.playerUsername.indexOf(player.data.username);
    if (usernameIndex >= 0) this.playerUsername.splice(usernameIndex, 1);

    // 移除playerlist
    delete this.playerList[ps.socket.id];
  }

  destroyRoom(key){
    Object.keys(this.playerList).forEach(k => {
      let item = this.playerList[k];
      if(item.data.room && item.data.room == key) {
        item.socket.leave(key);
        item.delete('room');
      }
    });
  }
}

class PS {
  constructor(socket) {
    this.socket = socket;
    this.data = {};

    this.status = false;

    this.set('id', socket.id);
    this.listen();
  }

  listen() {
    this.socket.on('all', data => {
      action.call(this, data)
    });
    this.socket.on('disconnect', () => {
      global.Core.player.leave(this);
      // 判断是否在房间中，如果在就退出
      if (this.data.room) {
        global.Core.room.leave(this);
      }
    })
  }

  set(key, val) {
    this.data[key] = val;
  }

  get(keys) {
    let result = {};
    Object.keys(keys).forEach(key => {
      result[key] = this.data[key]
    })
    return result;
  }

  delete(key) {
    delete this.data[key];
  }

  emit(name, data) {
    global.Core.socket.emit(name, data, this.socket);
  }
}

module.exports = Player;